import React, {useState} from 'react';
import {message, Modal, Steps} from 'antd';
import OrderInfo from './components/OrderInfo';
import PaymentMethods from './components/PaymentMethods';
import QRCodePayment from './components/QRCodePayment';
import CashPayment from './components/CashPayment';
import PaymentResult from './components/PaymentResult';
import styles from './style.less';
import {deleteOrderInfoById, orderInfoAdd, updateOrderInfoById} from "@/pages/order/order-edit/api";
import {parseNumber} from "@/utils/NumberUtils";
import {ICashModalInfo, IOrderData, IPaymentResult, OrderPaymentMethod} from "@/components/OrderPaymentModal/types";
import DateUtil from "@/utils/DateUtils";
import {AlipayF2FItem} from "@/services/pay/types";
import {payAlipayF2F, payWxF2F, queryOrderAlipay, queryOrderWx} from "@/services/pay/alipay";
import {OrderStatus} from "@/constants/OrderStatus";
import {API} from "@/services/typings";
import {orderRechargeSuccessAPI} from "@/pages/order/order-manager/services";
import moment from "moment";

const {Step} = Steps;

interface OrderPaymentModalProps {
  visible: boolean;
  orderData: IOrderData;
  onCancel: () => void;
  onGenerateOrder?: (order: API.IOrderInfo) => void;  // 订单信息保存到数据库时候发生回调
  onSuccess?: (order: API.IOrderInfo) => void;
  onResult?: () => void;
  onBackOrderInfo?: () => Promise<void>; // 从选择支付返回订单信息
}

const OrderPaymentModal: React.FC<OrderPaymentModalProps> = ({
                                                               visible,
                                                               orderData,
                                                               onCancel,
                                                               onResult,
                                                               onSuccess,
                                                               onGenerateOrder,
                                                               onBackOrderInfo
                                                             }) => {
    const [currentStep, setCurrentStep] = useState(0); // 当前支付流程步骤
    const [loading, setLoading] = useState(false);    // 加载状态
    const [paymentMethod, setPaymentMethod] = useState<OrderPaymentMethod | null>(null);  // 支付方式
    const [paymentResult, setPaymentResult] = useState<IPaymentResult | null>(null);  // 支付结果
    const [showQRCode, setShowQRCode] = useState(false);  // 显示二维码
    const [showCashModal, setShowCashModal] = useState(false);  // 显示现金支付确认模态框
    const [orderInfo, setOrderInfo] = useState<API.IOrderInfo | null>(null)
    const [cashModalInfo, setCashModalInfo] = useState<ICashModalInfo | null>(null)

    // 确认订单
    const handleSubmitOrder = async (address: API.ICustomerAddress) => {
      if (!address) {
        message.warning('请选择收货地址');
        return;
      }
      if (!orderData?.customer) {
        message.error('客户信息异常，请尝试重新下单');
        return;
      }
      setLoading(true);
      const {customer} = orderData
      const addressStr = [
        address?.province,
        address?.city,
        address?.district,
        address?.detailedAddress
      ].filter(Boolean).join(''); // 自动过滤空值
      const orderDetails: API.IOrderDetail[] = orderData.items.map((item) => {
        return {
          productId: item.id,
          productName: item.name || '',
          brand: item.brand || '',
          modelType: item.modelType || '',
          needReturn: item.needReturn || '1',
          unitPrice: parseNumber(item.amountUnit),
          number: parseNumber(item.rechargeCount),
          actualNum: item.actualCount || 0,
          payablePrice: item.amountPayable || 0,
          actualPrice: item.amountActual || 0,
          tongPrice: parseNumber(item.tongPrice),
          totalPrice: parseNumber(item.amountTotal),
          gouTongNumber: parseNumber(item.buyTongNum),
          huiTongNumber: parseNumber(item.returnTongNum),
          returnCash: item.returnPrice || 0,
          ticketNum: item.ticketNum || 0,
          status: '0',
          finalPrice: parseNumber(item.finalPrice),
        }
      })
      // 首先生成一条订单
      const orderInfo: API.IOrderInfo = {
        customerNumber: customer.customNumber,
        customerName: customer.name,
        contactName: address.contactName,
        phone: address.contactPhone,
        facilityId: orderData.facilityId || '',
        address: addressStr,
        customerAddressId: address.id,
        totalAmount: orderData.totalPayable,  // 商品应付金额
        productPaidAmount: orderData.totalPaid,  // 商品实付金额
        deposit: orderData.deposit,  // 押金
        paidAmount: Number(orderData.deposit || 0) + Number(orderData.totalPaid || 0),
        finalAmount: Number(orderData.deposit || 0) + Number(orderData.totalPaid || 0),
        returnCash: Number(orderData.totalCashback || 0),
        paidStatus: '0',
        orderStatus: OrderStatus.NEW_ORDER.value,
        source: '1',
        invoiceRequired: '1',
        orderDetailList: orderDetails,
        title: orderData.title ?? '购买商品',
        settlementType: '3',
        orderTime: DateUtil.formatDate(new Date()),
        type: orderData.type,
        deliveryStartTime: orderData.deliveryStartTime ? orderData.deliveryStartTime : moment('07:00', 'HH:mm').format('YYYY-MM-DD HH:mm:ss'),
        deliveryEndTime: orderData.deliveryEndTime ? orderData.deliveryEndTime : moment('19:00', 'HH:mm').format('YYYY-MM-DD HH:mm:ss'),
      } as any;
      const {data} = await orderInfoAdd(orderInfo)
      if (data) {
        setOrderInfo(data)
        message.success('订单生成成功')
        setCurrentStep(1);
        onGenerateOrder?.(data)
      } else {
        message.error('订单生成失败')
      }
      setLoading(false)
    };

    const handlePaymentMethodSelect = (method: OrderPaymentMethod) => {
      setPaymentMethod(method);
      if (method === 'cash') {
        // 现金支付显示确认模态框
        setCashModalInfo(null)
        setShowCashModal(true);
      } else if (method === 'monthly') {
        setCashModalInfo({
          title: '月结支付',
          tip: '请评估用户信用信息',
          tipFooter: <span>请仔细评估客户的信用信息，确认无误后点击<span
            style={{fontWeight: 'bold'}}>确认收款</span></span>,
        })
        setShowCashModal(true);
      } else if (method === 'wechat' || method === 'alipay') {
        // 电子支付显示二维码
        setShowQRCode(true);
      }
    };

    // 现金支付
    const handleCashPayment = async () => {
      if (!orderInfo || !orderInfo.id) {
        await message.error('订单信息异常，请刷新页面重试')
        return
      }
      setLoading(true);
      setShowCashModal(false);

      const payInfo: any = {}
      // 现金支付修改订单的状态为付款完成
      if (paymentMethod === 'cash') {
        payInfo.settlementType = '3' // 结款类型为下单支付
        payInfo.payMethod = '3'  // 现金支付
      } else if (paymentMethod === 'monthly') {
        payInfo.payMethod = '5'  // 现金支付
        payInfo.settlementType = '2'
      } else {
        message.error('无效的支付方式')
        setLoading(false);
        return
      }
      const {data} = await orderRechargeSuccessAPI({...payInfo, orderId: orderInfo.id})
      if (data) {
        setPaymentResult({
          success: true,
          orderNum: orderInfo.id,
          amount: orderInfo.paidAmount,
          paymentMethod,
          paidAt: DateUtil.getNowTime(),
        })
        if (onSuccess) onSuccess(orderInfo);
      } else {
        setPaymentResult({
          success: false,
          orderNum: orderInfo.id,
          amount: orderInfo.paidAmount,
          paymentMethod,
          paidAt: DateUtil.getNowTime(),
        })
        message.error('订单支付失败')
      }
      setCurrentStep(2);
      setLoading(false);
    };

    // 轮询支付宝支付状态
    const pollAlipayPaymentStatus = async (orderNum: string) => {
      const maxAttempts = 30; // 最大轮询次数
      const interval = 2000; // 轮询间隔2秒
      let attempts = 0;

      return new Promise<void>((resolve, reject) => {
        const poll = async () => {
          attempts++;
          try {
            // 调用查询支付宝支付状态的API
            const {data} = await queryOrderAlipay(orderNum);
            if (data.tradeQueryResponse.tradeStatus === 'TRADE_SUCCESS') {
              const {data} = await orderRechargeSuccessAPI({
                settlementType: '3',
                payMethod: '1',
                orderId: orderInfo?.id
              } as any)
              if (data) {
                setPaymentResult({
                  success: true,
                  orderNum: orderInfo?.id,
                  amount: orderInfo?.paidAmount,
                  paymentMethod,
                  paidAt: DateUtil.getNowTime(),
                } as any)
                setCurrentStep(2);
                resolve();
              }
              return;
            }
            // 如果未达到最大尝试次数，继续轮询
            if (attempts < maxAttempts) {
              setTimeout(poll, interval);
            } else {
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              reject(new Error('支付超时'));
            }
          } catch (error) {
            console.error('轮询支付状态失败:', error);
            if (attempts < maxAttempts) {
              setTimeout(poll, interval);
            } else {
              message.error('查询支付状态失败');
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              reject(error);
            }
          }
        };
        // 开始轮询
        poll();
      });
    };

    // 轮询微信支付状态
    const pollWechatPaymentStatus = async (orderNum: string) => {
      const maxAttempts = 30; // 最大轮询次数
      const interval = 2000; // 轮询间隔2秒
      let attempts = 0;

      return new Promise<void>((resolve, reject) => {
        const poll = async () => {
          attempts++;

          try {
            // 调用查询微信支付状态的API
            const {data} = await queryOrderWx(orderNum);

            if (data.trade_state === 'SUCCESS') {
              const {data} = await orderRechargeSuccessAPI({
                settlementType: '3',
                payMethod: '0',
                orderId: orderInfo?.id
              } as any)
              if (data) {
                setPaymentResult({
                  success: true,
                  orderNum: orderInfo?.id,
                  amount: orderInfo?.paidAmount,
                  paymentMethod,
                  paidAt: DateUtil.getNowTime(),
                } as any)
                setCurrentStep(2);
                resolve();
              }
              return;
            } else if (data.tradeState === 'CLOSED' || data.tradeState === 'REVOKED') {
              message.warning('交易已关闭或已撤销');
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              reject(new Error('交易已关闭或已撤销'));
              return;
            } else if (data.tradeState === 'PAYERROR') {
              message.error('支付失败');
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              reject(new Error('支付失败'));
              return;
            }

            // 继续轮询
            if (attempts < maxAttempts) {
              setTimeout(poll, interval);
            } else {
              message.warning('支付超时，请检查支付结果');
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              reject(new Error('支付超时'));
            }
          } catch (error) {
            console.error('轮询微信支付状态失败:', error);
            if (attempts < maxAttempts) {
              setTimeout(poll, interval);
            } else {
              setPaymentResult({
                success: false,
                orderNum: orderInfo?.id,
                amount: orderInfo?.finalAmount,
                paymentMethod,
                paidAt: DateUtil.getNowTime(),
              } as any)
              setCurrentStep(2);
              message.error('查询支付状态失败');
              reject(error);
            }
          }
        };

        // 开始轮询
        poll();
      });
    };

    const handleQRCodePayment = async (scannedCode: string) => {
      setLoading(true);
      if (!scannedCode) {
        message.warning('读取不到付款码信息')
        return
      }
      if (!orderInfo) {
        message.error('订单信息异常，请刷新页面重试')
        return
      }
      if (paymentMethod === 'alipay') {
        const orderItems: AlipayF2FItem[] = orderData.items.map(item => ({
          goodsId: item.id,
          goodsName: item.name,
          price: item.amountUnit + '',
          quantity: parseNumber(item.actualCount),
        }))
        const {data} = await payAlipayF2F({
          orderNum: orderInfo?.id || '',
          amount: orderInfo?.finalAmount + '',
          title: orderInfo?.title || '',
          orderItems: orderItems,
          authCode: scannedCode
        })
        if (data) {
          await pollAlipayPaymentStatus(orderInfo?.id)
          onSuccess?.(orderInfo)
        }
        setLoading(false)
      } else if (paymentMethod === 'wechat') {
        // 待接入微信付款
        const {data} = await payWxF2F({
          orderNum: orderInfo?.id || '',
          amount: orderInfo?.finalAmount + '',
          title: orderInfo?.title || '',
          authCode: scannedCode
        } as any)
        if (data) {
          await pollWechatPaymentStatus(orderInfo?.id)
          onSuccess?.(orderInfo)
        }
        setLoading(false)
      }
    };


    const steps = [
      {
        title: '订单确认',
        content: (
          <>
            <OrderInfo
              data={orderData}
              loading={loading}
              onSubmit={handleSubmitOrder}
              customer={orderData.customer}
              initAddress={orderData.address}
            />
          </>
        ),
      },
      {
        title: '支付方式',
        content: showQRCode ? (
          <QRCodePayment
            paymentMethod={paymentMethod || ''}
            amount={orderInfo?.finalAmount || 0}
            loading={loading}
            onPay={handleQRCodePayment}
            onBack={() => {
              setShowQRCode(false)
              setPaymentMethod(null)
            }}
          />
        ) : (
          <PaymentMethods
            amount={orderInfo?.finalAmount || 0}
            loading={loading}
            selectedMethod={paymentMethod || ''}
            onChangeMethod={handlePaymentMethodSelect}
            onBack={async () => {
              setCurrentStep(0)
              setPaymentMethod(null)
              // 删除订单信息
              if (!orderInfo) {
                return
              }
              await deleteOrderInfoById(orderInfo?.id)
              await onBackOrderInfo?.()
            }}
          />
        ),
      },
      {
        title: '支付结果',
        content:
          (
            <PaymentResult
              result={paymentResult as any}
              onClose={() => {
                onResult?.()
                onCancel?.()
              }}
              onRetry={() => {
                setCurrentStep(1);
                setShowQRCode(paymentMethod !== 'cash');
              }}
            />
          ),
      }
      ,
    ]

    return (
      <>
        <Modal
          title="订单支付"
          visible={visible}
          onCancel={onCancel}
          footer={null}
          width={800}
          className={styles.orderPaymentModal}
          destroyOnClose
          afterOpenChange={(open) => {
            setCurrentStep(0)
            if (open) {
              if (!orderData) {
                message.error('订单信息异常')
                onCancel()
              } else if (!orderData.items || !orderData.items.length) {
                message.error('获取不到商品信息，订单预览失败')
                onCancel()
              } else if (!orderData.customer) {
                message.error('获取不到客户信息，订单预览失败')
              }
            } else {
              setPaymentMethod(null)
              setShowQRCode(false)
              setShowCashModal(false)
              setPaymentResult(null)
            }
          }}
        >
          <div className={styles.stepsContainer}>
            <Steps
              type="navigation"
              current={currentStep} className={styles.steps}>
              {steps.map((item) => (
                <Step key={item.title} title={item.title}/>
              ))}
            </Steps>
          </div>
          <div className={styles.content}>{steps[currentStep].content}</div>
        </Modal>
        {/* 现金支付确认模态框 */}
        <CashPayment
          visible={showCashModal}
          amount={orderInfo?.finalAmount || 0}
          loading={loading}
          onOk={handleCashPayment}
          onCancel={() => {
            setShowCashModal(false)
            setPaymentMethod(null)
          }}
          info={cashModalInfo as any}
        />
      </>
    );
  }
;

export default OrderPaymentModal;
